import 'dart:math';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_demo/routers/router_paths.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart'; // 用于倒计时计时器

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage>
    with SingleTickerProviderStateMixin {
  Timer? _timer;
  int _countDown = 5;

  /// 倒计时的方法
  void _startCountDown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _countDown--;
        if (_countDown <= 0) {
          timer.cancel();
          context.replaceNamed(RouterPaths.home);
        }
      });
    });
  }

  late AnimationController _animationController;

  /// 构建加载中的文本
  Widget _buildLoadingText() {
    return AnimatedBuilder(
      animation: _animationController,
      builder: (_, child) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "加载中",
              style: TextStyle(color: Colors.black87, fontSize: 18.sp),
            ),
            // 三个点的动画效果
            ...List.generate(3, (index) {
              // 计算每个点的动画值，使它们依次显示
              final animationValue = sin(
                _animationController.value * 2 * pi + index * 2 * pi / 3,
              );
              // 根据动画值计算透明度（-1到1之间映射到0到1）
              final opacity = (animationValue + 1) / 2;

              return Padding(
                padding: EdgeInsets.symmetric(horizontal: 2.0.w),
                child: Opacity(
                  opacity: opacity,
                  child: Text(
                    ".",
                    style: TextStyle(fontSize: 18.sp, color: Colors.black87),
                  ),
                ),
              );
            }),
          ],
        );
      },
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    )..repeat();

    _startCountDown();
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _animationController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 1. 添加 Scaffold 作为页面根布局，设置背景色（如白色）
    return Scaffold(
      backgroundColor: Colors.white, // 显式设置页面背景为白色（解决黑色背景）
      appBar: null,

      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(8.0.r),
          child: Column(
            children: [
              Align(
                alignment: Alignment.topRight,
                child: OutlinedButton(
                  style: ButtonStyle(
                    padding: WidgetStateProperty.all(
                      EdgeInsets.symmetric(horizontal: 15.w, vertical: 5.h),
                    ),
                    minimumSize: WidgetStateProperty.all(Size(30.w, 20.h)),
                    textStyle: WidgetStateProperty.resolveWith((state) {
                      return TextStyle(fontSize: 12.sp);
                    }),
                    foregroundColor: WidgetStateProperty.resolveWith((state) {
                      return Colors.black87;
                    }),
                  ),
                  onPressed: () {
                    // 跳转到登录页
                    context.replaceNamed(RouterPaths.home);
                  },
                  child: Text.rich(
                    TextSpan(
                      children: [
                        TextSpan(text: "跳过"),
                        if (_countDown > 0) TextSpan(text: "$_countDown"),
                      ],
                    ),
                  ),
                ),
              ),

              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      height: 50.w,
                      width: 50.w,
                      child: CircularProgressIndicator(
                        backgroundColor: Colors.grey[500],
                        valueColor: const AlwaysStoppedAnimation<Color>(
                          Colors.red,
                        ), // 进度条颜色
                        strokeWidth: 5.sp, // 进度条粗细
                      ),
                    ),
                    SizedBox(height: 16.sp),
                    _buildLoadingText(),
                  ],
                ),
              ),
              Text(
                "本app仅用作演示用，不涉及任何商业用途",
                style: TextStyle(color: Colors.black87, fontSize: 14.sp),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
